package org.istt.web;


import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.SessionAware;
import org.istt.domain.User;
import org.istt.service.UserManager;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ChangePasswordAction extends ActionSupport implements SessionAware{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1444072119092590099L;
	private final Log log = LogFactory.getLog(ChangePasswordAction.class);
    private User user;
    private UserManager userManager;
    private String newPass;
    private String retypeNewPass;
    private Map<String, Object> session;
    
	public String getNewPass() {
		return newPass;
	}

	public void setNewPass(String newPass) {
		this.newPass = newPass;
	}

	public String execute() {
        
        return SUCCESS;
    }
    

	public User getUser() {
		return user;
	}
	
	public UserManager getUserManager() {
		return userManager;
	}
	
	public String changePassword(){
    	if(user!=null){
    		User acc = (User)userManager.login(user.getUsername(), user.getPassword());
        	if(acc != null){
        		log.debug("===Change password to: "+newPass);
        		// Check valid retype password
        		if(retypeNewPass!=null && !"".equals(retypeNewPass) && 
        				newPass!=null && !"".equals(newPass) && 
        				newPass.equals(retypeNewPass)){
        			acc.setPassword(newPass);
            		userManager.save(acc);
            		ActionContext.getContext().getSession().put("message", getText("changepass.success"));
            		
            		return SUCCESS;
        		}else{
        			ActionContext.getContext().getSession().put("message", getText("changepass.error.not.same.password"));
        			
            		return WebConstants.FAILURE;
        		}
        		
        	} else {
                ActionContext.getContext().getSession().put("message", getText("changepass.error"));
        		return WebConstants.FAILURE;
        	}
        	
    	}else{
    		return WebConstants.FAILURE;
    	}
    }

	public void setUser(User user) {
		this.user = user;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public void setRetypeNewPass(String retypeNewPass) {
		this.retypeNewPass = retypeNewPass;
	}

	public String getRetypeNewPass() {
		return retypeNewPass;
	}
}